using APITransLib.Contracts;
using ChatWithMulitAIServer.Data;
using Microsoft.AspNetCore.Mvc;

namespace ChatWithMulitAIServer.Controllers;

[ApiController]
[Route("api/messages")]
public class MessagesController(IChatRepository repo) : ControllerBase
{
    [HttpPost("send/{fromUserId}")]
    public async Task<ActionResult<SendMessageResponse>> Send(string fromUserId, SendMessageRequest req, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(fromUserId)) return BadRequest();
        if (req.ToUserId is null && req.ToGroupId is null) return BadRequest("to required");
        var msg = await repo.AddMessageAsync(fromUserId, req.ToUserId, req.ToGroupId, req.Kind, req.Content, ct);
        return Ok(new SendMessageResponse { Message = msg });
    }

    [HttpGet("user/{userId}")]
    public async Task<ActionResult<PagedResponse<MessageDto>>> ForUser(string userId, [FromQuery] int skip = 0, [FromQuery] int take = 50, CancellationToken ct = default)
    {
        var items = await repo.GetMessagesForUserAsync(userId, skip, take, ct);
        return Ok(new PagedResponse<MessageDto> { Total = items.Count, Items = items });
    }

    [HttpGet("group/{groupId}")]
    public async Task<ActionResult<PagedResponse<MessageDto>>> ForGroup(string groupId, [FromQuery] int skip = 0, [FromQuery] int take = 50, CancellationToken ct = default)
    {
        var items = await repo.GetMessagesForGroupAsync(groupId, skip, take, ct);
        return Ok(new PagedResponse<MessageDto> { Total = items.Count, Items = items });
    }
}
